<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="workType"
        placeholder="工卡执行类型"
        clearable
        style="width: 190px"
        class="filter-item"
      >
        <el-option v-for="item in workTypes" :key="item" :label="item" :value="item"/>
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >移动工卡信息下载</el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="workdatas"
      stripe
      fit
      highlight-current-row
      style="width: 100%;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="选择" type="selection" width="40px" />
      <el-table-column type="expand">
        <template slot-scope="props">
          <!-- {{ props.row[header] }} -->
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item v-for="header in workheader" :key="header" :label="header">
              <span>{{ props.row[header] }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column
        v-for="header in fixedworkheader"
        :prop="header"
        :label="header"
        :key="header"
        align="center">
        <!-- <template slot-scope="scope">
          <span v-if="header==='ID'" class="link-type" @click="routeTo(scope.row.workuid)">{{ scope.row['ID'] }}</span>
          <span v-else>{{ scope.row[header] }}</span>
        </template> -->
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import { requestWorklist, requestAttachment } from '@/api/workcard'
import { saveWorkcard, getWorklist } from '@/utils/storage'
import { saveAttachment, savePhoto, deletePhoto } from '@/utils/file'
import { mergeExistWorkcard, getWorkcardID } from '@/utils/workcard-util'

export default {
  data() {
    return {
      fixedworkheader: ['ID', '名称', '工卡类型', '编制', '机型号', '架机号'],
      workheader: [],
      workdatas: [],
      workType: '',
      selectedWorkcards: [],
      worklist: [],
      workTypes: [
        '所有类型',
        '测试系统检查',
        '测试校准',
        'J1 机械安装',
        'J1 机械拆除',
        '机械生产准备',
        'D4 机械检查、试验及配合工作',
        '机械称重',
        'D3 电气安装',
        'D3 电气拆除',
        '电气检查、试验及配合工作',
        '电气盒体机柜类制作',
        '电气线缆地面制作',
        '电气线缆机上敷设',
        '电气线缆机上制作'
      ],
      loading: false
    }
  },
  watch: {
    workType(selectedValue) {
      this.getWorkCardDataAndHeaderByType(selectedValue)
    }
  },
  methods: {
    ...mapMutations([
      'ADD_WORKINSTRUCTION_ROUTERS'
    ]),
    getWorkCardDataAndHeaderByType(workType) {
      const that = this
      that.workheader = ['ID', '名称', '工卡类型', '编制', '机型号', '架机号']
      if (!this.$store.state.app.online) {
        this.$message.error('离线状态下不能获取服务器工卡！')
        return
      }
      this.loading = true
      that.workdatas = []
      that.worklist = []
      if (!this.$store.state.app.online) {
        this.$message.error('离线状态下不能获取服务器工卡！')
        return
      }
      requestWorklist().then(
        response => {
          const all = response.data
          for (var i = 0; i < all.length; i++) {
            if (all[i].worktype === workType || workType === '所有类型') {
              const workcard = {}
              workcard.workuid = all[i].workuid
              all[i].workrelattrs.forEach(
                attr => {
                  if (that.workheader.indexOf(attr.name) === -1) {
                    that.workheader.push(attr.name)
                  }
                  workcard[attr.name] = attr.value || ''
                }
              )
              workcard['工卡类型'] = all[i].worktype
              that.workdatas.push(workcard)
              that.worklist.push(all[i])
            }
          }
          console.log(that.workdatas)
        }
      ).catch(
        err => {
          console.log(err)
          if (err.message === 'Network Error') {
            that.$message.error('网络错误，未连接到服务器！')
          }
        }
      ).finally(
        () => {
          that.loading = false
        }
      )
    },
    handleDownload() {
      if (!this.$store.state.app.online) {
        this.$message.error('离线状态下不能下载工卡！')
        return
      }
      const that = this
      let count = 0
      let error = {}
      if (this.selectedWorkcards.length === 0) {
        this.$message.warning('请选择所需下载的工卡！')
        return
      }

      this.loading = true
      for (var i = 0; i < this.selectedWorkcards.length; i++) {
        for (var j = 0; j < this.worklist.length; j++) {
          if (this.selectedWorkcards[i]['workuid'] === this.worklist[j].workuid) {
            if ('isfinished' in this.worklist[j] === false && 'isFinished' in this.worklist[j] === false) {
              this.worklist[j].isfinished = 'False'
            }

            if ('isFinished' in this.worklist[j]) {
              this.worklist[j].isfinished = this.worklist[j].isFinished || 'False'
              delete this.worklist[j].isFinished
            }

            if ('isfinished' in this.worklist[j] && !this.worklist[j].isfinished) {
              this.worklist[j].isfinished = 'False'
            }

            mergeExistWorkcard(this.worklist[j]).then(
              arrObj => {
                const mergedWorkcard = arrObj[0]
                const newPhotoObjects = arrObj[1]
                const deletePhotoObjects = arrObj[2]
                const attachementObjects = arrObj[3]

                saveWorkcard(mergedWorkcard)

                newPhotoObjects.forEach(
                  photoObject => {
                    if (photoObject.uid) {
                      count++
                      requestAttachment(photoObject.uid).then(
                        blob => {
                          console.log('[download]-[handleDownload]-download photo: ' + photoObject.path + ', size: ' + blob.size)
                          const id = getWorkcardID(mergedWorkcard)
                          savePhoto(id, photoObject.path, blob)
                        }
                      ).catch(
                        err => {
                          console.log('[download]-[handleDownload]-download photo err: ')
                          console.log(err)
                          error = err
                        }
                      ).finally(
                        () => {
                          count--
                          console.log('count:' + count)
                          if (count === 0) {
                            that.loading = false
                            if (JSON.stringify(error) !== '{}') {
                              if (error.message === 'Network Error' || error.message === 'Failed to fetch') {
                                that.$message.error('网络错误，未连接到服务器！')
                              } else {
                                that.$message.error(error)
                              }
                            } else {
                              that.$message.success('工卡下载成功！')
                            }
                          }
                        }
                      )
                    }
                  }
                )
                attachementObjects.forEach(
                  attachment => {
                    if (attachment.uid) {
                      count++
                      requestAttachment(attachment.uid).then(
                        blob => {
                          console.log('[download]-[handleDownload]-download attachment: ' + attachment.path + ', size: ' + blob.size)
                          const id = getWorkcardID(mergedWorkcard)
                          saveAttachment(id, attachment.path, blob)
                        }
                      ).catch(
                        err => {
                          console.log('[download]-[handleDownload]-download attachment err: ')
                          console.log(err)
                          error = err
                        }
                      ).finally(
                        () => {
                          count--
                          console.log('count:' + count)
                          if (count === 0) {
                            that.loading = false
                            if (JSON.stringify(error) !== '{}') {
                              if (error.message === 'Network Error' || error.message === 'Failed to fetch') {
                                that.$message.error('网络错误，未连接到服务器！')
                              } else {
                                that.$message.error(error)
                              }
                            } else {
                              that.$message.success('工卡下载成功！')
                            }
                          }
                        }
                      )
                    }
                  }
                )

                deletePhotoObjects.forEach(photoObject => {
                  const id = getWorkcardID(mergedWorkcard)
                  deletePhoto(id, photoObject.path)
                })

                count++
                getWorklist().then(
                  worklist => {
                    const newItems = []
                    for (var i = 0; i < worklist.length; i++) {
                      const newItem = {
                        path: worklist[i].workcard.workuid,
                        component: () => import('@/views/workcard/workcard'),
                        props: { workuid: worklist[i].workcard.workuid },
                        name: worklist[i].workcard.workuid,
                        meta: { title: worklist[i].workcard.workrelattrs.find(v => v.name === 'ID').value, noCache: 'true' }
                      }
                      newItems.push(newItem)
                    }
                    that.ADD_WORKINSTRUCTION_ROUTERS(newItems)
                  }
                ).catch(
                  err => {
                    console.log('[download]-[handleDownload]-getWorkList err: ')
                    console.log(err)
                    error = '工卡读取错误！'
                  }
                ).finally(
                  () => {
                    count--
                    console.log('count:' + count)
                    if (count === 0) {
                      that.loading = false
                      if (JSON.stringify(error) !== '{}') {
                        if (error.message === 'Network Error' || error.message === 'Failed to fetch') {
                          that.$message.error('网络错误，未连接到服务器！')
                        } else {
                          that.$message.error(error)
                        }
                      } else {
                        that.$message.success('工卡下载成功！')
                      }
                    }
                  }
                )
              }
            ).catch(
              err => {
                console.log(err)
              }
            )
          }
        }
      }
    },
    handleSelectionChange(val) {
      this.selectedWorkcards = val
    }
  }
}
</script>

<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>
